<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      v-show="showSearch"
    >
    <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="" prop="guideName">
        <el-input
          v-model="queryParams.guideName"
          placeholder="指南标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="" prop="projectName">
        <el-select
              v-model="queryParams.projectName"
              placeholder="项目名称"
              clearable
              style="width: 100%"
              @keyup.enter.native="handleQuery"
            >
              <el-option
                v-for="dict in dict.type.sys_project_name"
                :key="dict.value"
                :label="dict.label"
                :value="dict.label"
              />
        </el-select>
      </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="" prop="guideType">
       <el-cascader v-model="queryParams.guideType" :options="options" placeholder="指南类别"  ref="queryPartRef" @change="queryHanChange"  style="width:100%" @keyup.enter.native="handleQuery">
          </el-cascader>
      </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="">
            <el-date-picker
              v-model="createTime"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="创建开始日期"
              end-placeholder="创建结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      
      
      
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :disabled='multiple'
        >导出</el-button>
      </el-col> -->
      <!-- <right-toolbar
        @dataChange="dataChange"
        :storageKey="$options.name"
        @changeColumns="changeColumns"
        ref="table"
        :showSearch.sync="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="guideList"
      ref="newsTable"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="指南标题" align="center" prop="guideName" :show-overflow-tooltip="true" />
      <el-table-column label="项目名称" align="center" prop="projectName" :show-overflow-tooltip="true" />
      <el-table-column label="指南类别" align="center" prop="guideType" :show-overflow-tooltip="true"/>
      <el-table-column label="操作人" align="center" prop="createBy" width="200"/>
      <el-table-column label="创建日期" sortable align="center" prop="createTime" width="200"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <el-table
      row-key="key"
      :key="isShow"
      v-loading="loading"
      :data="guideList"
      ref="guideTable"
      @selection-change="handleSelectionChange"
    >
      <template v-for="item in columns">
        <el-table-column
          v-if="item.visible && item.type"
          type="selection"
          :key="Math.random()"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          :key="Math.random()"
          v-if="item.visible && !item.type"
          :class-name="item.className"
          :prop="item.prop"
          :label="item.label"
          :align="item.align"
          :type="item.type"
          :width="item.width"
        >
          <template slot-scope="scope">
            <template v-if="item.htmlType == 'imageUpload' && item.visible">
              <image-preview :src="scope.row[item.prop]" :width="50" :height="50" />
            </template>

            <template v-else-if="item.htmlType == 'datetime' && item.visible">
              <span>{{ parseTime(scope.row[item.prop], '{y}-{m}-{d}') }}</span>
            </template>

            <template v-else-if="item.htmlType == 'checkbox' && item.visible">
              <dict-tag
                v-if="item.htmlType == 'checkbox'"
                :options="dict.type[item.dictType]"
                :value="scope.row[item.prop] ? scope.row[item.prop].split(',') : []"
              />
              <dict-tag v-else :options="dict.type[item.dictType]" :value="scope.row[item.prop]" />
            </template>
            <template v-else-if="item.htmlType =='operation'">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:guide:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:guide:remove']"
              >删除</el-button>
            </template>
            <template v-else>
              <span>{{ scope.row[scope.column.property] }}</span>
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table> -->

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增或修改申请指南维护对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="指南标题" prop="guideName">
          <el-input v-model="form.guideName" placeholder="请输入指南名称" />
        </el-form-item>
        <el-form-item label="指南类别" prop="guideType">
          <el-cascader v-model="form.guideType" :options="options"  ref="partRef" @change="formHanChange"  style="width:100%">
          </el-cascader>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-select
              v-model="form.projectName"
              placeholder="选择类别后自动填充"
              clearable
              :disabled="true"
              style="width: 100%"
            >
              <el-option
                v-for="dict in dict.type.sys_project_name"
                :key="dict.value"
                :label="dict.label"
                :value="dict.label"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="指南内容" prop="guideComment">
          <!-- <el-input v-model="form.guideComment" type="textarea" placeholder="请输入内容" /> -->
          <JEditor :key="showdis" v-model="form.guideComment" :height="350" />
        </el-form-item>
        <!-- <el-form-item label="指南附件" prop="attachment">
                <RoadUpload
                  v-model="form.attachment"
                  :fileType="fileType"
                  :fileSize="fileSize"
                  :flag="isFlag"
                ></RoadUpload>
              </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGuide,
  getGuide,
  delGuide,
  addGuide,
  updateGuide
} from "@/api/businessModule/guide";
import {getArrayInfo, getTreeSelect } from "@/api/workflow/model";
import RoadUpload from "../../../components/RoadUpload/index.vue";
// import { setStorageItem, getStorageItem } from "@/utils/storage.js";
// import Sortable from "sortablejs";
export default {
  name: "Guide",
  dicts:['sys_project_name'],
  components: {
    RoadUpload,
  },
  data() {
    return {
      // 是否显示格式
      isFlag:false,
      isShow: false,
      // 级联选择器
      options:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      guideNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 申请指南维护表格数据
      guideList: [],
      // 弹出层标题
      title: "",
      showdis: 123,
      // 是否显示弹出层
      open: false,
      //时间范围
      createTime:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        guideName: null,
        guideType: null,
        projectName:null,
      },
      // 列信息
      // columns: [
      //   {
      //     key: -1,
      //     label: "主键",
      //     visible: true,
      //     prop: "guideId",
      //     htmlType: "input",
      //     dictType: "",
      //     align: "center"
      //   },
      //   {
      //     key: 0,
      //     label: "指南名称",
      //     visible: true,
      //     prop: "guideName",
      //     htmlType: "input",
      //     dictType: "",
      //     align: "center"
      //   },
      //   {
      //     key: 1,
      //     label: "指南类型",
      //     visible: true,
      //     prop: "guideType",
      //     htmlType: "select",
      //     dictType: "",
      //     align: "center"
      //   },
      //   {
      //     key: 2,
      //     label: "指南内容",
      //     visible: true,
      //     prop: "guideComment",
      //     htmlType: "textarea",
      //     dictType: "",
      //     align: "center"
      //   },
      //   {
      //     key: 3,
      //     label: "创建人",
      //     visible: true,
      //     prop: "createBy",
      //     htmlType: "input",
      //     dictType: "",
      //     align: "center"
      //   },
      //   {
      //     key: 4,
      //     label: "创建时间",
      //     visible: true,
      //     prop: "createTime",
      //     htmlType: "datetime",
      //     dictType: "",
      //     align: "center"
      //   },
      //   {
      //     key: 5,
      //     label: "更新人",
      //     visible: true,
      //     prop: "updateBy",
      //     htmlType: "input",
      //     dictType: "",
      //     align: "center"
      //   },
      //   {
      //     key: 6,
      //     label: "更新时间",
      //     visible: true,
      //     prop: "updateTime",
      //     htmlType: "datetime",
      //     dictType: "",
      //     align: "center"
      //   },
      //   {
      //     key: 0,
      //     label: `操作`,
      //     visible: true,
      //     prop: "operation",
      //     htmlType: "operation",
      //     align: "center",
      //     width: "200",
      //     className: "fixed-width"
      //   }
      // ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        guideName: [
          { required: true, message: "指南标题不能为空", trigger: "blur" },
          // { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        guideType: [
          { required: true, message: "指南类别不能为空", trigger: "blur" }
        ],
        guideComment: [
          { required: true, message: "指南内容不能为空", trigger: "blur" }
        ],
        attachment: [
          { required: false, message: "指南附件不能为空", trigger: "blur" }
        ],
      },
      // 级联选择器的lable
      labels: [],
      // 查询条件级联的lable
      queryLabels: null,
      fileType: [],
      fileSize:50,
    };
  },
  created() {
    // let data = getStorageItem(this.$options.name);
    // if (data) {
    //   this.columns = data;
    // }
    this.getTreeSelect()
    this.getList();
  },
  // mounted() {
  //   this.columnDrop();
  // },
  methods: {
    //列拖拽
    // columnDrop() {
    //   const wrapperTr = this.$refs.guideTable.$el.querySelector(
    //     ".el-table__header-wrapper tr"
    //   );
    //   this.sortable = Sortable.create(wrapperTr, {
    //     animation: 180,
    //     delay: 30,
    //     // draggable: ".drag",
    //     onEnd: evt => {
    //       if (evt.oldIndex === evt.newIndex) return;
    //       const oldItem = this.columns[evt.oldIndex];
    //       const newItem = this.columns[evt.newIndex];
    //       this.$set(this.columns, evt.newIndex, oldItem);
    //       this.$set(this.columns, evt.oldIndex, newItem);
    //       setStorageItem(this.$options.name, this.columns);
    //     }
    //   });
    // },
    // dataChange(data) {
    //   for (let item in this.columns) {
    //     const key = this.columns[item].key;
    //     this.columns[item].visible = !data.includes(key);
    //   }

    //   setStorageItem(this.$options.name, this.columns);
    // },
    // changeColumns(data) {
    //   this.columns = data;
    //   setStorageItem(this.$options.name, data);
    //   this.isShow = !this.isShow;
    // },
    // 查询级联
    queryHanChange() {
      let queryNames = this.$refs.queryPartRef.getCheckedNodes();
      if (queryNames[0] !== null) {
        queryNames.forEach(element => {
          this.queryLabels = element.pathLabels
        }); 
        }
    },
    // 表单级联选择器
    formHanChange(val) {
      let names = this.$refs.partRef.getCheckedNodes();
      if (names[0] !== null) {
        names.forEach(element => {
          this.labels = element.pathLabels
          this.form.projectName = element.label
        }); 
        }
        
      
    },
    async getTreeSelect() {
      const res = await getTreeSelect({
        type:'业务类型'
      })
     this.options = res.data
    },

    /** 查询申请指南维护列表 */
    getList() {
      this.loading = true;
      let obj = { ...this.queryParams }
      if (this.queryLabels == null) {
        obj = obj
      } else {
        obj.guideType = this.queryLabels.toString().replace(',','/')
      }
      listGuide(this.addDateRange(obj,this.createTime)).then(response => {
        this.guideList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        guideId: null,
        guideName: null,
        guideType: null,
        guideComment: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.fileType = [],
      this.fileSize = 50
      this.resetFormData("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryLabels = null,
      this.createTime = []
      this.resetFormData("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.guideId);
      this.guideNames = selection.map(item => item.guideName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 调用字典接口
    async gitDictType() {
      const res = await this.getDicts('attr_type')
      const Arr = res.data
      Arr.map(item => {
        return this.fileType.push(item.dictLabel)
      })
      const resSize = await this.getDicts('attr_size')
      this.fileSize = Number(resSize.data[0].dictValue)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.gitDictType()
      this.getTreeSelect()
      this.open = true;
      this.showdis = Math.random();
      this.title = "新增办事指南";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      this.gitDictType()
      this.getTreeSelect()
      const guideId = row.guideId || this.ids;
       const response = await getGuide(guideId)
        this.form = response.data;
        this.form.guideType = response.data.tier.split(',')
        this.open = true;
        this.showdis = Math.random();
        this.title = "修改办事指南";
      this.$nextTick(() => {
        this.formHanChange()
      })
      
      // const categoryArr = row.category.replace('/', ',').split(',')
      // this.categoryOptions.filter(k => {
      //   categoryArr.some(item => {
      //     if (k.categoryName == item) {
      //       categoryIds.push(k.categoryId)
      //       this.labels.push(k.categoryName)
      //     }
      //   })
      // })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.guideId != null) {
            updateGuide({ ...this.form,guideType:this.labels.toString().replace(',','/'),tier:this.form.guideType.toString() }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGuide({ ...this.form,guideType:this.labels.toString().replace(',','/'),tier:this.form.guideType.toString() }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const guideIds = row.guideId || this.ids;
      const guideNames = row.guideName || this.guideNames;
      this.$modal
        .confirm('是否确认删除申请办事指南标题为"' + guideNames + '"的数据项？')
        .then(function() {
          return delGuide(guideIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/guide/export",
        {
          ...this.queryParams
        },
        `guide_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
